package com.wz.app.http;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.LruCache;
import android.widget.ImageView;

public class LoadImage extends AsyncTask<String, String, Bitmap> {

	private ImageView imageView;
	private LruCache<String, Bitmap> cache;
	

	public LoadImage(ImageView imageView,LruCache<String, Bitmap> cache) {
		super();
		this.imageView = imageView;
		this.cache = cache;
		
	}
	public Bitmap getBitMapFromCache(String url) {
		return cache.get(url);
	}

	public void setBitMapToCache(String url, Bitmap bitmap) {
		cache.put(url, bitmap);
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		// TODO Auto-generated method stub
		Bitmap bitmap = null;
		//获取传进来的图片url
		String url = params[0];
		//判断图片是否有缓存到lurcache 没有则从网络取出，有则直接使用
		if (cache.get(url)==null) {
			try {
				URL ur = new URL(url);
				HttpURLConnection conn= (HttpURLConnection) ur.openConnection();
				InputStream stream = conn.getInputStream();
				
				bitmap = BitmapFactory.decodeStream(stream);
				cache.put(url, bitmap);
				conn.disconnect();
				stream.close();
			//	System.out.println("cache--------==="+cache.hashCode());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			bitmap = cache.get(url);
		}
		return bitmap;
	}
	
	@Override
	protected void onPostExecute(Bitmap bitmap) {
		// TODO Auto-generated method stub
		super.onPostExecute(bitmap);
		imageView.setImageBitmap(bitmap);
	}
 
	@Override
	protected void onCancelled() {
		// TODO Auto-generated method stub
		super.onCancelled();
	}

}
